package com.app.shortvideo.utils

import android.app.Activity
import android.net.Uri
import android.text.TextUtils
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import com.app.shortvideo.BuildConfig
import com.app.shortvideo.config.Constant
import com.app.shortvideo.ui.common.WebViewActivity
import com.app.library.utils.openId.OpenUDID_manager
import com.blankj.utilcode.util.LogUtils

fun WebView.initWeb(activity: Activity?) {
    settings.apply {
        javaScriptEnabled = true
        builtInZoomControls = true
        setSupportZoom(false)
        layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        loadWithOverviewMode = true
        useWideViewPort = true
        savePassword = false
        cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        domStorageEnabled = true
        blockNetworkImage = false
//        userAgentString = userAgentString + ";" + MAppUtils.buildUserAgent()
    }

    addJavascriptInterface(
        WebJavascriptInterface(this, activity ?: return),
        WebViewActivity.JS_HANDLER_OBJECT_NAME
    )
    if (BuildConfig.DEBUG) WebView.setWebContentsDebuggingEnabled(true)
    isHorizontalScrollBarEnabled = false //水平不显示
    isVerticalScrollBarEnabled = false //垂直不显示
}

fun WebView.setWebCookie(url: String?) {
    val cookieManager = CookieManager.getInstance()
    cookieManager.removeSessionCookies(null)
    cookieManager.setCookie(url, "MaxityInnerBrowser=true")
    cookieManager.setCookie(url, "version=" + BuildConfig.VERSION_CODE)
//        if (Session.isSessionOpend()) {
//            val cookieString = "credential=" + Session.tryToGetAccessToken()
//            cookieManager.setCookie(url, cookieString)
//        }
    CookieManager.getInstance().flush()
}

fun WebView.loadWeb(url: String?) {
    url ?: return
    setWebCookie(url)
    val header = HashMap<String, String>()
    header[Constant.DEVICE_ID] = OpenUDID_manager.getOpenUDID()
    val uri = Uri.parse(url)
    val articleId = uri.getQueryParameter("articleId")
    val builder = java.lang.StringBuilder(url)
    if (!TextUtils.isEmpty(articleId)) {
        builder.append("&").append("taskId").append("=").append(1)
    }
    LogUtils.e("Web", "加载 url = $builder")
    loadUrl(builder.toString(), header)
}